﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using RobotRace.engine.agents.implementation;

namespace RobotRaceGUI.AgentConfigurationForms
{
    public partial class PIDPointFollowerConfigurationForm : Form
    {
        public PIDPointFollower agent { get; set; }

        public PIDPointFollowerConfigurationForm()
        {
            InitializeComponent();
        }

        public PIDPointFollowerConfigurationForm(PIDPointFollower agent) : this()
        {
            this.agent = agent;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double maxVelocity = 1.0;
            double startingStepSpeed = 0.5;
            double turningSpeedModifier = 0.2;
            double addedErrorWeight = 0.0;
            double addedDerivativeWeight = 0.001;

            try
            {
                maxVelocity = convertAndThrowIfNotValidDouble(maxVelocityTextBox.Text, "max valocity");
                startingStepSpeed = convertAndThrowIfNotValidDouble(startingStepSpeedTextBox.Text, "starting step speed");
                turningSpeedModifier = convertAndThrowIfNotValidDouble(turningSpeedModifierTextBox.Text, "turning speed modifier");
                addedErrorWeight = convertAndThrowIfNotValidDouble(addedErrorWeightTextBox.Text, "added error weight");
                addedDerivativeWeight = convertAndThrowIfNotValidDouble(addedDerivativeWeightTextBox.Text, "added derivative weight");

            }
            catch (ValueNotValidException ex)
            {
                MessageBox.Show("The value of" + ex.FieldName + " does not seem to be valid. Please verify it and try again.");
                return;
            }

            agent.maxVelocity = maxVelocity;
            agent.startingStepSpeed = startingStepSpeed;
            agent.turningSpeedModifier = turningSpeedModifier;
            agent.addedErrorWeight = addedErrorWeight;
            agent.addedDerivativeWeight = addedDerivativeWeight;

            this.Hide();

        }

        private double convertAndThrowIfNotValidDouble(String value, String fieldName)
        {
            try
            {
                return Double.Parse(value);
            }
            catch (Exception ex)
            {
                throw new ValueNotValidException("Exception while parsing field value!", fieldName);
            }
        }

        private void PIDPointFollowerConfigurationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }
    }
}
